package com.example.adminvue.controller;

import com.example.adminvue.domain.*;
import com.example.adminvue.service.ISysRoleService;
import com.example.adminvue.service.ISysUserService;
import com.example.adminvue.service.SysDeptService;
import com.example.adminvue.service.SysPostService;
import com.example.adminvue.utils.SecurityUtils;
import com.example.adminvue.utils.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private SysDeptService deptService;

    @Autowired
    private SysPostService postService;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(User user)
    {
        startPage();
        List<User> list = userService.selectUserList(user);
        TableDataInfo tableDataInfo = getDataTable(list);
        List<User> userList = (List<User>) tableDataInfo.getRows();
        for (int i = 0; i <userList.size() ; i++) {
            SysDept dept = deptService.selectDeptById(userList.get(i).getDeptId());
            userList.get(i).setDeptName(dept.getDeptName());
            List<SysRole> roleList = roleService.rolesByUserId(userList.get(i).getUserId());
            if(roleList.size() > 0){
                List<Long> roleids = roleList.stream().map(SysRole::getRoleId).collect(Collectors.toList());
                Long[] roleidArray = new Long[roleids.size()];
                roleidArray=roleids.toArray(roleidArray);
                userList.get(i).setRoles(roleList);
                userList.get(i).setRoleIds(roleidArray);
                userList.get(i).setRoleId(roleids.get(0));
            }
        }
        return tableDataInfo;
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        List<Long> posts = postService.selectPostListByUserId(userId);
        ajax.put("roles", User.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        if (StringUtils.isNotNull(userId))
        {
            User User = userService.selectUserById(userId);
            ajax.put("data", User);
            ajax.put("roleIds", User.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
            ajax.put("postIds",posts);
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @PostMapping
    public AjaxResult add(@Validated @RequestBody User user)
    {
        user.setCreateBy(getUsername());
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody User user)
    {
        userService.checkUserAllowed(user);
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        if (ArrayUtils.contains(userIds, getUserId()))
        {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        User user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", User.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

}
